# 扫描并连接BLE设备，读取电池电量特征
from bleak import BleakScanner, BleakClient

async def read_battery():
    devices = await BleakScanner.discover(timeout=20, return_adv=True)


    for key, value in devices.items():
        if key not in ("06:05:0C:90:A2:68", ):
            continue
        # print(value, value[1].manufacturer_data.get(2072, b"").decode(encoding="gb2312"))

        async with BleakClient(key) as client:
            # 检查是否连接成功
            if not client.is_connected:
                print(f"连接失败{key} {value}")
                return
            services = client.services
            for service in services:
                print(f"\n服务UUID: {service}")
                # 服务UUID解析（判断是否为标准服务）
                if service.uuid.startswith("0000") and len(service.uuid) == 36:
                    # 提取16位标准UUID（如0000180f-... → 0x180f）
                    short_uuid = f"0x{service.uuid[4:8]}"
                    print(f"  标准服务UUID: {short_uuid}")
                
                # 新增：遍历服务下所有特征
                for char in service.characteristics:
                    print(f"  特征UUID: {char.uuid}")
                    if char.uuid.startswith("0000") and len(char.uuid) == 36:
                        short_char_uuid = f"0x{char.uuid[4:8]}"
                        print(f"    标准特征UUID: {short_char_uuid}")
                    
                    # 新增：打印描述符信息
                    for descriptor in char.descriptors:
                        print(f"    描述符UUID: {descriptor.uuid}")
                        if descriptor.uuid.startswith("0000") and len(descriptor.uuid) == 36:
                            short_desc_uuid = f"0x{descriptor.uuid[4:8]}"
                            print(f"      标准描述符UUID: {short_desc_uuid}")
            # 电池服务UUID：0x180F，电量特征UUID：0x2A19
            # 尝试读取电池电量特征
            target_char_uuid = "00002a05-0000-1000-8000-00805f9b34fb"
            found = False
            for service in client.services:
                for char in service.characteristics:
                    if char.uuid == target_char_uuid:
                        # 找到目标特征，尝试读取
                        try:
                            battery_level = await client.read_gatt_char(char)
                            print(f"电池电量：{battery_level[0]}%")
                            found = True
                            break
                        except Exception as e:
                            print(f"读取特征时出错: {e}")
                if found:
                    break
            if not found:
                print(f"未找到特征 {target_char_uuid}。可用特征列表：")
                for service in client.services:
                    print(f"\n服务UUID: {service.uuid}")
                    for char in service.characteristics:
                        print(f"  特征UUID: {char.uuid}")

import asyncio
asyncio.run(read_battery())